const knex = async (query, page, pageSize) => {
  const count = await query.clone().count('id as count')
  const total = count[0]['count']
  let data = await query
    .offset((page - 1) * pageSize) 
    .limit(pageSize)
    .select()

  page = page || 1
  return {
    total,
    page,
    pageSize,
    data
  }
}

const bookshelf = async (q, page, pageSize, withRelated) => {
  const data = await q.fetchPage({
    pageSize, // Defaults to 10 if not specified
    page, // Defaults to 1 if not specified
    withRelated // Passed to Model#fetchAll
  })
  page = +page
  const total = await q.count()

  return {
    total,
    page,
    pageSize,
    data
  }
}

module.exports = {
  knex,
  bookshelf
}